// HJ68.[stable_sort]成绩排序
// https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b  [较难]
// std::stable_sort(b,e,cmp)
// 给定一些同学的信息（名字，成绩）序列，
// 请你将他们的信息按照成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理。
// jack    70
// peter   96
// Tom     70
// smith   67
// 从高到低  成绩
// peter   96
// jack    70
// Tom     70
// smith   67
// 从低到高
// smith   67
// jack    70
// Tom     70
// peter   96

#include <algorithm>
#include <iostream>
#include <tuple>
#include <vector>
using namespace std;

typedef tuple<int, string, int> Student;  // id, name, score
#define STU_id 0
#define STU_name 1
#define STU_score 2

bool Cmp_Greater(const Student& st1, const Student& st2) {
  return get<STU_score>(st1) < get<STU_score>(st2);
}

bool Cmp_Less(const Student& st1, const Student& st2) {
  return get<STU_score>(st1) > get<STU_score>(st2);
}

vector<Student> score_sort(const vector<Student>& vtStudent,
                           bool bSortGreater) {
  vector<Student> res(vtStudent);
  if (bSortGreater) {
    std::stable_sort(res.begin(), res.end(), Cmp_Greater);
  } else {
    std::stable_sort(res.begin(), res.end(), Cmp_Less);
  }
  return res;
}

int main_hj68() {
  int count = 0;
  int sortGreat = 0;
  cin >> count;
  cin >> sortGreat;
  vector<Student> vtStu(count);
  for (int i = 0; i < count; i++) {
    string name;
    int score = 0;
    cin >> name >> score;
    vtStu[i] = {i, name, score};
  }

  vector<Student> out = score_sort(vtStu, sortGreat);
  for (auto [name, score] : out) {
    printf("%s %d\n", name.c_str(), score);
  }
  return 0;
}
